/**
 * 
 */
package cn.edu.nju.ws.sview.wyge.relations.adataset.overview;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author Weiyi Ge (geweiyi@gmail.com) 2012-7-27
 * 
 */
public class PrintGraph {
	public static int[] print(String tmpDirectory, String ds_type, int ds_id) throws IOException {
		String picture = tmpDirectory + ds_type + ds_id + ".svg";
		String tmpdot = tmpDirectory + ds_type + ds_id + ".dot";
		
		if ((new File(picture)).exists()) {
			boolean dgraph = false;
			while (!dgraph) {
				dgraph = (new File(picture)).delete();
			}
		}

		Runtime.getRuntime().exec("dot -Tsvg " + tmpdot + " -o " + picture);
		boolean isdelete = false;
		while (!isdelete) {
			File pic = new File(picture);
			int[] dem = getDemension(picture);
			if (pic.exists() && dem[0] != 0 && dem[1] != 0){
				File tmp = new File(tmpdot);
				isdelete = tmp.delete();
			}
		}
		
		return getDemension(picture);
	}
	
	private static int[] getDemension(String picture) throws IOException {
		int[] demension = new int[2];
		if (!new File(picture).exists())
			return demension;
		BufferedReader br = new BufferedReader(
				new FileReader(new File(picture)));
		String line = "";
		while ((line = br.readLine()) != null) {
			if (line.startsWith("<svg width=")) {
				line = line.substring(12);
				String[] tp = line.split("pt\" height=\"");
				demension[0] = Integer.parseInt(tp[0]);
				demension[1] = Integer.parseInt(tp[1].substring(0,
						tp[1].length() - 3));
				break;
			}
		}
		br.close();
		return demension;
	}
}
